import { getJobList, addJob, updateJob, deleteJob, startJob, pauseJob, runJobOnce } from '@/api/job'

const job = {
  state: {
    jobList: [],
    total: 0,
    currentJob: null
  },
  mutations: {
    SET_JOB_LIST: (state, list) => {
      state.jobList = list
    },
    SET_JOB_TOTAL: (state, total) => {
      state.total = total
    },
    SET_CURRENT_JOB: (state, job) => {
      state.currentJob = job
    }
  },
  actions: {
    // 获取任务列表
    getJobList({ commit }, params) {
      return new Promise((resolve, reject) => {
        getJobList(params).then(response => {
          const { data, total } = response.data
          commit('SET_JOB_LIST', data)
          commit('SET_JOB_TOTAL', total)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 新增任务
    addJob({ dispatch }, jobForm) {
      return new Promise((resolve, reject) => {
        addJob(jobForm).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 更新任务
    updateJob({ dispatch }, { id, jobForm }) {
      return new Promise((resolve, reject) => {
        updateJob(id, jobForm).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 删除任务
    deleteJob({ dispatch }, id) {
      return new Promise((resolve, reject) => {
        deleteJob(id).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 启动任务
    startJob({ dispatch }, id) {
      return new Promise((resolve, reject) => {
        startJob(id).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 暂停任务
    pauseJob({ dispatch }, id) {
      return new Promise((resolve, reject) => {
        pauseJob(id).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    // 立即执行一次任务
    runJobOnce({ dispatch }, id) {
      return new Promise((resolve, reject) => {
        runJobOnce(id).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default job
